//
//  StoreViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-31.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "StoreViewController.h"
#import "CityData.h"
#import "StoreCell.h"
#import "AppDelegate.h"
#import "MapViewController.h"
#import "MainViewController.h"
#import "Place.h"

@implementation StoreViewController
@synthesize brandCategoryLabel;
@synthesize storeTitle;
@synthesize scrollView;
@synthesize mTableView;
@synthesize citys;
@synthesize stores;
@synthesize brandData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //brandCategoryId = 1;
        //cityId = -1;
        //self.citys = [CityData getAllItems];
        //self.stores = [StoreData getAllItems];
        gpsHelper = [[GPSHelper alloc] init];
        gpsHelper.delegate = self;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [brandData release];
    [gpsHelper release];
    [categoryView release];
    [brandCategoryLabel release];
    [storeTitle release];
    [citys release];
    [stores release];
    [scrollView release];
    [mTableView release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)addCityButton:(CityData *)city andFrame:(CGRect)frame andFont:(UIFont *)font {
    UIButton *cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cityButton.frame = frame;
    cityButton.titleLabel.font = font;
    [cityButton setBackgroundColor:[UIColor whiteColor]];
    [cityButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cityButton setTitle:city.name forState:UIControlStateNormal];
    [cityButton addTarget:self action:@selector(cityButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    NSInteger cid = [city.cityID intValue];
    cityButton.tag = 100 +cid;
    [scrollView addSubview:cityButton];
}

- (void)cityButtonClick:(id)sender {
    UIButton *cityButton = (UIButton *)sender;
    NSInteger cid = cityButton.tag - 100;
    if (cid == cityId) {
        return;
    }
    cityId = cid;
    if (selectButton) {
        [selectButton setBackgroundColor:[UIColor whiteColor]];
        [selectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    selectButton = cityButton;
    [selectButton setBackgroundColor:[UIColor blackColor]];
    [selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    if (brandCategoryId == 1) {
        self.stores = [StoreData getItemsByCityId:cityId];
    } else {
        self.stores = [StoreData getItemsByCityId:cityId brandId:brandCategoryId];
    }
    if ([stores count] == 0) {
        mTableView.hidden = YES;
    } else {
        mTableView.hidden = NO;
    }
    [mTableView reloadData];
}

- (NSInteger)getTextWidth:(NSString*)str font:(UIFont*)font {
	CGFloat lineHeight = font.lineHeight * 2;
	CGSize bounds = CGSizeMake( 10000, lineHeight);
	
	CGSize size = [str sizeWithFont:font constrainedToSize:bounds lineBreakMode:UILineBreakModeTailTruncation];
	
	return size.width;
}

- (void)reloadCitys {
    NSArray *subViews = scrollView.subviews;
    for (UIView *view in subViews) {
        [view removeFromSuperview];
    }
    UIFont *font = [UIFont boldSystemFontOfSize:14];
    int x=0, y=4, w=50, h=40;
    CGRect frame;
    for (CityData *city in citys) {
        w = [self getTextWidth:city.name font:font] + 20;
        frame = CGRectMake(x, y, w, h);
        [self addCityButton:city andFrame:frame andFont:font];
        x += w;
    }
    scrollView.contentSize = CGSizeMake(x, y + h + y);
}

- (void)initCityByBrand:(BrandData *)data {
    brandCategoryId = [data.brandID intValue];
    if (brandCategoryId == 1) {
        self.stores = [StoreData getAllItems];
    } else {
        self.stores = [StoreData getItemsByBrandId:brandCategoryId];
    }
    NSMutableSet *storeCitys = [NSMutableSet setWithCapacity:5];
    for (StoreData *data in stores) {
        [storeCitys addObject:data.cityID];
    }
    NSMutableArray *newCitys = [NSMutableArray arrayWithCapacity:5];
    for (NSString *cid in storeCitys) {
        CityData * data = [CityData getItemByID:cid];
        [newCitys addObject:data];
    }
    self.citys = newCitys;
}

- (void)addLogoView:(NSString *)imageUrl { 
    logoView = [[SyncImageView alloc] initWithUrl:imageUrl andRequestQueue:requestQueue];
    logoView.frame = CGRectMake(10, 5, 124, 64);
    [storeTitle addSubview:logoView];
    [logoView release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    mTableView.dataSource = self;
    mTableView.delegate = self;
    
    brandCategoryId = 1;
    cityId = -1;
    if (brandData) {
        brandCategoryId = [brandData.brandID intValue];
    }
    
    if (brandCategoryId == 1) {
        self.citys = [CityData getAllItems];
        self.stores = [StoreData getAllItems];
    } else {
        [self initCityByBrand:brandData];
    }
 

    
    [self reloadCitys];
    
    BrandData *defaultCategoryData = nil;
    NSArray *brandCategorys = [BrandData getAllItems];
    for (BrandData *categoryData in brandCategorys) {
        if ([@"1" isEqualToString:categoryData.brandID]) {
            categoryData.name = [AppDelegate getLanguageString:@"brand_category_all"];
            defaultCategoryData = categoryData;
        }
    }
    categoryView = [[AboutCategoryViewController alloc] initWithNibName:@"AboutCategoryViewController" bundle:nil];
    categoryView.brands = brandCategorys;
    categoryView.delegate = self;
    categoryView.view.frame = CGRectMake(0, -392, 320, 392);
    [self.view addSubview:categoryView.view];
    
    if (brandCategoryId == 1) {
        if (defaultCategoryData) {
            brandCategoryLabel.text = [NSString stringWithFormat:@"%@ (%d)", defaultCategoryData.name, [stores count]];
            [self addLogoView:defaultCategoryData.logo];
        }
    } else {
        brandCategoryLabel.text = [NSString stringWithFormat:@"%@ (%d)", brandData.name, [stores count]];
        [self addLogoView:brandData.logo];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)showMenuAnimation:(UIView*)view {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1];
	[UIView setAnimationDelay:0.0];
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 416);
    view.transform = transform;
	[UIView commitAnimations];
}

- (IBAction)showBrandSelect:(id)sender {
    [self showMenuAnimation:categoryView.view];
}

- (IBAction)searchNearStores:(id)sender {
    [gpsHelper startLocation];
}

- (NSArray *)initNearStores:(CLLocationCoordinate2D)coordinate {
	CLLocation *locationCoordinate = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    NSArray *allStores = self.stores;//[StoreData getAllItems];
    NSInteger minDistance = 9999 * 1000;
    StoreData *minStoreData = nil;
    for (StoreData *data in allStores) {
        CLLocation *dataCoordinate = [[CLLocation alloc] initWithLatitude:[data.latitude floatValue] longitude:[data.longitude floatValue]];
        NSInteger distance = (NSInteger)[locationCoordinate distanceFromLocation:dataCoordinate];
        //NSLog(@"id(%@) distance=%d", data.storeID, distance);
        if (distance < minDistance) {
            minDistance = distance;
            minStoreData = data;
        }
        [dataCoordinate release];
    }
    [locationCoordinate release];
    
    NSMutableArray *nearStores = [[[NSMutableArray arrayWithCapacity:5] retain] autorelease];
    if (minStoreData != nil) {
        NSInteger maxDistance = 1000 * 10;//10Km
        CLLocation *locationCoordinate = [[CLLocation alloc] initWithLatitude:[minStoreData.latitude floatValue] longitude:[minStoreData.longitude floatValue]];
        for (StoreData *data in allStores) {
            CLLocation *dataCoordinate = [[CLLocation alloc] initWithLatitude:[data.latitude floatValue] longitude:[data.longitude floatValue]];
            NSInteger distance = (NSInteger)[locationCoordinate distanceFromLocation:dataCoordinate];
            //NSLog(@"id(%@) distance=%d", data.storeID, distance);
            if (distance < maxDistance) {
                [nearStores addObject:data];
            }
            [dataCoordinate release];
        }
        [locationCoordinate release];
    }
    return nearStores;
}

- (void)updataHeading:(CLLocationDirection)heading {
    ;
}

- (void)jumpToMapView:(NSArray *)places local:(CLLocationCoordinate2D)coordinate {
    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapViewController.places = places;
    mapViewController.location = [[[Place alloc] initWithLatitude:coordinate.latitude andlongitude:coordinate.longitude andTitle:nil andDetail:nil] autorelease];
    MainViewController *mainView = (MainViewController *)mainViewController;
    [mainView pushViewController:mapViewController];
    [mapViewController release];
}

- (void)updataLocation:(CLLocationCoordinate2D)coordinate {
    [gpsHelper stopLocation];
    NSArray *nearStores = [self initNearStores:coordinate];
    NSMutableArray *places = [NSMutableArray arrayWithCapacity:[nearStores count]];
    for (StoreData *data in nearStores) {
        Place *p = [[Place alloc] initWithLatitude:[data.latitude floatValue] andlongitude:[data.longitude floatValue] andTitle:data.name andDetail:nil];
        [places addObject:p];
        [p release];
    }
    [self jumpToMapView:places local:coordinate];
}

- (void)jumpToMapView:(NSArray *)places {
    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapViewController.places = places;
    MainViewController *mainView = (MainViewController *)mainViewController;
    [mainView pushViewController:mapViewController];
    [mapViewController release];
}

- (void)changeViewController:(BrandData *)data {
    if (brandCategoryId == [data.brandID intValue]) {
        return;
    }
    [self initCityByBrand:data];
    /*
    brandCategoryId = [data.brandID intValue];
    if (brandCategoryId == 1) {
        self.stores = [StoreData getAllItems];
    } else {
        self.stores = [StoreData getItemsByBrandId:brandCategoryId];
    }*/
    brandCategoryLabel.text = [NSString stringWithFormat:@"%@ (%d)",data.name , [stores count]];
    if ([stores count] == 0) {
        mTableView.hidden = YES;
    } else {
        mTableView.hidden = NO;
    }
    [mTableView reloadData];
    /*
    NSMutableSet *storeCitys = [NSMutableSet setWithCapacity:5];
    for (StoreData *data in stores) {
        [storeCitys addObject:data.cityID];
    }
    NSMutableArray *newCitys = [NSMutableArray arrayWithCapacity:5];
    for (NSString *cid in storeCitys) {
        CityData * data = [CityData getItemByID:cid];
        [newCitys addObject:data];
    }
    cityId = -1;
    self.citys = newCitys;
    */
    cityId = -1;
    [self reloadCitys];
    
    if (logoView) {
        [logoView removeFromSuperview];
        logoView = nil;
    }
    [self addLogoView:data.logo];
    /*NSString *imageUrl = data.logo;
    logoView = [[SyncImageView alloc] initWithUrl:imageUrl andRequestQueue:requestQueue];
    logoView.frame = CGRectMake(10, 5, 124, 64);
    [storeTitle addSubview:logoView];
    [logoView release];*/
}

#pragma mark -
#pragma mark Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [stores count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"StoreCellIdentifier";
    
    StoreCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"StoreCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    // Configure the cell...
	NSUInteger row = [indexPath row];
	StoreData *rowData = [stores objectAtIndex:row];
    [cell config:self data:rowData];
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//changeViewController();
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 127;
}

@end
